package com.xiumu.common.core.enums.converter;

import com.xiumu.common.core.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.stream.Stream;

/**
 * 枚举值 code 映射成对应的枚举类
 *
 * @Author XiuMu
 * @Date 2023/3/10 21:37
 **/
public class CodeToEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new CodeConverterToEnum<>(targetType);
    }

    /**
     * 映射的具体实现类
     */
    static class CodeConverterToEnum<T extends BaseEnum> implements Converter<String, T> {

        private final Class<T> enumType;

        public CodeConverterToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String code) {
            return Stream.of(enumType.getEnumConstants())
                    .filter(item -> item.getCode().equals(Integer.valueOf(code)))
                    .findAny().orElse(null);
        }
    }
}
